package com.lu.test.aop;


import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;

public class CGLibProxyTest2 {
	public static void main(String[] args) {
		// 生成的代理对象的存放位置
		System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,"D:\\code\\spring-framework-main\\spring-framework-main");

		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(A.class);
		enhancer.setCallback(new CglibProxyTest());

		A o = (A) enhancer.create();
		System.out.println(o.test());

	}
}

class A {
	private String filed;

	private List<String> fileds;

	public String getFiled() {
		return filed;
	}

	public void setFiled(String filed) {
		this.filed = filed;
	}

	public List<String> getFileds() {
		return fileds;
	}

	public void setFileds(List<String> fileds) {
		this.fileds = fileds;
	}

	public A() {
		System.out.println("a constructor");
	}

	// final 无法被代理
	public final String test2() {
		System.out.println("hello world2");
		return "result2";
	}

	public String test() {
		System.out.println("hello world");
		return "result";
	}
}

class CglibProxyTest implements MethodInterceptor {


	/**
	 * @param sub         被增强的对象（A）
	 * @param method      被拦截的方法
	 * @param args        被拦截方法的参数
	 * @param methodProxy 被增强的对象的方法对象（原生对象的方法对象）
	 * @return
	 * @throws Throwable
	 */
	@Override
	public Object intercept(Object sub, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
		System.out.println("before");
		Object o = methodProxy.invokeSuper(sub, args);
		System.out.println("after");
		return o;
	}
}